<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 顶部导航栏复用代拿员样式 -->
    <header class="bg-white border-b border-gray-200 sticky top-0 z-50">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
          <div class="flex items-center gap-3">
            <div class="w-10 h-10 bg-blue-600 rounded-lg overflow-hidden">
              <img src="../../../头像.jpg" alt="头像" class="w-full h-full object-cover" />
            </div>
            <span class="text-xl font-semibold text-gray-900">校园快递代拿</span>
            <span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded">代拿员</span>
          </div>
          <HeaderActions />
        </div>
      </div>
    </header>

    <!-- 面包屑 -->
    <div class="bg-white border-b border-gray-200">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-2 text-sm text-gray-500">
        <button class="hover:text-blue-600" @click="$router.push('/courier/orders')">我的订单</button>
        <span class="mx-2">/</span>
        <span class="hover:text-blue-600 cursor-pointer" @click="$router.push('/courier/order/detail/' + orderId)">订单详情</span>
        <span class="mx-2">/</span>
        <span class="text-gray-900">评价下单者</span>
      </div>
    </div>

    <!-- 内容 -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 左：订单进度（复用详情页样式） -->
        <section class="lg:col-span-2 bg-white rounded-lg shadow-sm p-6">
          <h2 class="text-lg font-semibold text-gray-900 mb-4">订单进度</h2>
          <ol class="relative border-l-2 border-gray-300 ml-4 text-sm">
            <li class="mb-6 ml-4" v-for="(step, idx) in steps" :key="idx">
              <div
                class="absolute w-3 h-3 rounded-full -left-1.5 border"
                :class="idx <= currentStep ? 'bg-blue-600 border-blue-600' : 'bg-white border-gray-300'"
              ></div>
              <time class="text-gray-400">{{ step.time }}</time>
              <div class="text-gray-900 font-medium">{{ step.title }}</div>
              <div class="text-gray-500">{{ step.desc }}</div>
            </li>
          </ol>
        </section>

        <!-- 右：评价区域 -->
        <aside class="bg-white rounded-lg shadow-sm p-6 h-fit">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">评价下单者</h3>
          <p class="text-sm text-gray-500 mb-4">订单编号：{{ orderId }}</p>

          <!-- 星级评分 -->
          <div class="mb-4">
            <div class="flex items-center gap-2 mb-1">
              <span class="text-sm text-gray-700">综合评分</span>
              <span class="text-sm text-blue-600" v-if="score">{{ score }} 分</span>
            </div>
            <div class="flex items-center gap-1">
              <button
                v-for="n in 5"
                :key="n"
                type="button"
                class="w-8 h-8 flex items-center justify-center rounded-full border border-transparent hover:border-yellow-400"
                @click="score = n"
              >
                <svg
                  class="w-6 h-6"
                  :class="n <= score ? 'text-yellow-400' : 'text-gray-300'"
                  fill="currentColor"
                  viewBox="0 0 20 20"
                >
                  <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.286 3.967a1 1 0 00.95.69h4.178c.969 0 1.371 1.24.588 1.81l-3.383 2.459a1 1 0 00-.364 1.118l1.287 3.966c.3.922-.755 1.688-1.54 1.118L10 15.347l-3.953 2.708c-.784.57-1.838-.196-1.539-1.118l1.287-3.966a1 1 0 00-.364-1.118L2.048 9.394c-.783-.57-.38-1.81.588-1.81h4.178a1 1 0 00.95-.69l1.285-3.967z" />
                </svg>
              </button>
            </div>
          </div>

          <!-- 文字评价 -->
          <div class="mb-4">
            <label class="block text-sm text-gray-700 mb-2">评价内容（可选）</label>
            <textarea
              v-model="comment"
              rows="4"
              placeholder="可以简单说说这次合作体验，比如沟通是否顺畅、付款是否及时等"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none text-sm"
            ></textarea>
          </div>

          <!-- 提交按钮 -->
          <div class="flex flex-col gap-3">
            <button
              type="button"
              class="w-full py-2.5 rounded-lg text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:hover:bg-blue-600"
              :disabled="submitting || !score"
              @click="submitRating"
            >
              {{ submitting ? '提交中...' : '提交评价' }}
            </button>
            <button
              type="button"
              class="w-full py-2.5 rounded-lg text-sm font-medium text-gray-600 border border-gray-300 hover:bg-gray-50"
              @click="$router.back()"
            >
              取消
            </button>
          </div>
        </aside>
      </div>
    </main>
  </div>
</template>

<script>
import axios from 'axios'
import HeaderActions from '../components/HeaderActions.vue'
export default {
  name: 'CourierOrderRate',
  components: { HeaderActions },
  data() {
    return {
      orderId: this.$route.params.id,
      steps: [],
      currentStep: 0,
      score: 5,
      comment: '',
      submitting: false
    }
  },
  methods: {
    async loadOrderProgress() {
      try {
        const { data } = await axios.get(`/api/orders/${this.orderId}`)
        const d = (data && data.data) || {}
        const fmt = (v) => (v ? String(v).replace('T', ' ').slice(0, 19) : '—')
        const status = Number(d.status) || 1

        const created = fmt(d.created_at)
        const accepted = fmt(d.accepted_at)
        const picked = fmt(d.picked_up_at || d.accepted_at)
        const delivered = fmt(d.delivered_at || d.picked_up_at || d.accepted_at)
        const completed = fmt(d.completed_at || d.updated_at)

        this.steps = [
          { title: '已下单', desc: '用户提交订单', time: created },
          { title: '已接单', desc: '代拿员已接单', time: accepted },
          { title: '已取件', desc: '已取件配送中', time: picked },
          { title: '已送达', desc: '已通知用户取件', time: delivered },
          { title: '已完成', desc: '订单已完成', time: completed }
        ]

        this.currentStep = Math.min(Math.max(status - 1, 0), this.steps.length - 1)
      } catch (e) {
        console.error('加载订单进度失败', e)
      }
    },
    async submitRating() {
      if (!this.score) {
        alert('请先选择评分')
        return
      }
      const me = Number(localStorage.getItem('userId'))
      if (!me) {
        this.$router.push('/login')
        return
      }
      if (this.submitting) return
      this.submitting = true
      try {
        const payload = { orderId: Number(this.orderId), courierId: me, score: this.score }
        const { data } = await axios.post('/api/users/order-users/rate', payload)
        if (data && data.success) {
          alert('评价已提交，感谢反馈')
          this.$router.push('/courier/orders')
        } else {
          alert((data && data.message) || '评价失败，请稍后再试')
        }
      } catch (e) {
        console.error('提交评价失败', e)
        alert('提交评价失败，请稍后再试')
      } finally {
        this.submitting = false
      }
    }
  },
  mounted() {
    this.loadOrderProgress()
  }
}
</script>
